<?php

namespace App\Http\Logic\PC;

use App;
use App\Common\Status;
use App\Models\Note;
use App\Models\EducationalBack;
use App\Models\NotesIntention;
use App\Models\NotesMiddle;
use App\Models\Resources;
use App\Models\WorkExp;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;
use PHPUnit\TextUI\Help;

class NoteLogic
{
    use App\Http\Logic\NoteOtherLogic;

    /**
     * @param $params
     * @param int $source
     * @return mixed
     * @throws \Exception
     */
    public static function createResume($params, $source = 1)
    {
        $eg = Note::where('mobile', $params['mobile'])->first();
        if ($eg) {
            if ($params['id']) {
                if ($params['id'] != $eg->id) {
                    return ["status" => Status::ERROR, "msg" => "该手机号已被注册"];
                }
            } else {
                return ["status" => Status::ERROR, "msg" => "该手机号已被注册"];
            }
        }
        $educationalBack = $params['educational_back'] ?? [];
        $project_exp     = $params['project_exp'] ?? [];
        $work_exp        = $params['work_exp'] ?? [];
        $notesIntention  = $params['notes_intention'] ?? [];
        $annexId         = $params['annex_id'] ?? '';
        $attName         = $params['att_name'] ?? '';
        unset($params['educational_back']);
        unset($params['project_exp']);
        unset($params['work_exp']);
        unset($params['notes_intention']);


        if (empty($params['weChat'])) {
            unset($params['weChat']);
        }

        $params['cell_mobile'] = $params['mobile'];

        if ($source == 2) {
            unset($params['annex_id']);
            unset($params['att_name']);
            $dt                  = Helper::timediff(time(), strtotime($params['work_date']));
            $yearsDiff           = ceil($dt["day"] / 365);
            $params['work_year'] = $yearsDiff;
            $params['birth']     = strtotime($params['birth']);
            $params['work_date'] = strtotime($params['work_date']);
        } else {
            $dt                  = Helper::timediff(time(), floor($params['work_date'] / 1000));
            $yearsDiff           = ceil($dt["day"] / 365);
            $params['work_year'] = $yearsDiff;
            $params['birth']     = floor($params['birth'] / 1000);
            $params['work_date'] = floor($params['work_date'] / 1000);
            $params['mobile']    = Helper::pcByMobile();
        }
        # 获取学历
        $edus       = array_column($educationalBack, "education");
        $connection = DB::connection('mysql');
        $connection->beginTransaction();
        try {
            if ($params['id']) {
                $id = $params['id'];
                if ($source == 2) {
                    self::createAnnex($id, $annexId, $params['mobile'], $attName);
                }
                self::createEducationalBack($id, $params['mobile'], $educationalBack);
                self::createWorkExp($id, $params['mobile'], $project_exp, $work_exp);
                self::createreNotesIntention($id, $params['mobile'], $notesIntention,
                    $params['work_year'], $edus);
                $params['updated_at'] = time();
                unset($params['id']);
                Note::where('id', $id)->update($params);
                $connection->commit();
                return ["status" => Status::SUCCESS];
            }

            unset($params['id']);
            $params['source']     = 2;  # 标识符 1 pc用户创建，2后台创建
            $params['created_at'] = time();

            $id = Note::insertGetId($params);

            if ($source == 2) {
                self::createAnnex($id, $annexId, $params['mobile'], $attName);
            }
            self::createEducationalBack($id, $params['mobile'], $educationalBack);
            self::createWorkExp($id, $params['mobile'], $project_exp, $work_exp);
            self::createreNotesIntention($id, $params['mobile'], $notesIntention,
                $params['work_year'], $edus);
            $connection->commit();
            return ["status" => Status::SUCCESS, "id" => $id];
        } catch (\Exception $exception) {
            $connection->rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 附件
     * @param $id
     * @param $annexId
     * @param $mobile
     * @param $attName
     */
    private static function createAnnex($id, $annexId, $mobile, $attName)
    {
        if ($id) {
            DB::table("recruit_notes_middle")->where([['mobile', '=', $mobile]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
        }

        DB::table("recruit_notes_middle")->insert(["mobile" => $mobile, "res_id" => $annexId, "att_name" => $attName, "created_at" => time()]);
    }

    /**
     * @param $id
     * @param $mobile
     * @param $educationalBack
     */
    private static function createEducationalBack($id, $mobile, $educationalBack)
    {
        if ($id) {
            EducationalBack::where([['mobile', '=', $mobile]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
        }

        if ($educationalBack && count($educationalBack) > 0) {
            $newEducationalBack = [];
            if ($educationalBack && count($educationalBack) > 0) {
                foreach ($educationalBack as $k => $addr) {
                    $newEducationalBack[$k]['job_notes_id']    = $id;
                    $newEducationalBack[$k]['university_name'] = $addr['university_name'];
                    $newEducationalBack[$k]['education']       = $addr['education'];
                    $newEducationalBack[$k]['speciality']      = $addr['speciality'];
                    $newEducationalBack[$k]['st_date_st']      = floor($addr['st_date_st'] / 1000);
                    $newEducationalBack[$k]['st_date_ed']      = floor($addr['st_date_ed'] / 1000);
                    $newEducationalBack[$k]['mobile']          = $mobile;
                    $newEducationalBack[$k]['created_at']      = time();
                }
                EducationalBack::insert($newEducationalBack);
            }
        }
    }

    /**
     * 添加意向
     * @param $id
     * @param $mobile
     * @param $notesIntention
     * @param $work_year
     * @param $edus
     */
    private static function createreNotesIntention($id, $mobile, $notesIntention, $work_year, $edus)
    {
        if ($id) {
            NotesIntention::where([['mobile', '=', $mobile], ['job_notes_id', '=', $id]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
        }

        if ($notesIntention && count($notesIntention) > 0) {
            $eduString = implode(',', $edus);

            $newNotesIntention = [];
            if ($notesIntention && count($notesIntention) > 0) {
                foreach ($notesIntention as $k => $ni) {
                    $newNotesIntention[$k]['job_notes_id']         = $id;
                    $newNotesIntention[$k]['education']            = $eduString;
                    $newNotesIntention[$k]['work_province']        = $ni["work_province"];
                    $newNotesIntention[$k]['work_city']            = $ni["work_city"];
                    $newNotesIntention[$k]['salary1']              = $ni["salary1"];
                    $newNotesIntention[$k]['salary2']              = $ni["salary2"];
                    $newNotesIntention[$k]['position_category_id'] = $ni["position_category_id"];
                    $newNotesIntention[$k]['job_type']             = $ni["job_type"];
                    $newNotesIntention[$k]['mobile']               = $mobile;
                    $newNotesIntention[$k]['work_year']            = $work_year;
                    $newNotesIntention[$k]['created_at']           = time();
                }
                NotesIntention::insert($newNotesIntention);
            }
        }
    }

    /**
     * @param $id
     * @param $mobile
     * @param $project_exp
     * @param $work_exp
     * @return mixed
     */
    private static function createWorkExp($id, $mobile, $project_exp, $work_exp)
    {
        if ($id) {
            WorkExp::where('mobile', $mobile)->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
        }
        $new_project_exp = $new_work_exp = [];
        if ($project_exp && count($project_exp) > 0) {
            foreach ($project_exp as $k => $p) {
                $new_project_exp[$k]['tp']            = 2;
                $new_project_exp[$k]['job_notes_id']  = $id;
                $new_project_exp[$k]['business_name'] = $p['business_name'];
                $new_project_exp[$k]['position_name'] = $p['position_name'];
                $new_project_exp[$k]['work_exp']      = $p['work_exp'];
                $new_project_exp[$k]['work_name']     = $p['work_name'];
                $new_project_exp[$k]['salary']        = null;


                $new_project_exp[$k]['work_date_st'] = floor($p['work_date_st'] / 1000);
                $new_project_exp[$k]['work_date_ed'] = floor($p['work_date_ed'] / 1000);
                $new_project_exp[$k]['mobile']       = $mobile;
                $new_project_exp[$k]['created_at']   = time();
            }
            WorkExp::insert($new_project_exp);
        }
        if ($work_exp && count($work_exp) > 0) {
            foreach ($work_exp as $kw => $w) {
                $new_work_exp[$kw]['tp']            = 1;
                $new_work_exp[$kw]['job_notes_id']  = $id;
                $new_work_exp[$kw]['business_name'] = $w['business_name'];
                $new_work_exp[$kw]['position_name'] = $w['position_name'];
                $new_work_exp[$kw]['work_exp']      = $w['work_exp'];
                $new_work_exp[$kw]['salary']        = $w['salary'];
                $new_work_exp[$kw]['work_date_st']  = floor($w['work_date_st'] / 1000);
                $new_work_exp[$kw]['work_date_ed']  = floor($w['work_date_ed'] / 1000);
                $new_work_exp[$kw]['mobile']        = $mobile;
                $new_work_exp[$kw]['created_at']    = time();
            }
            WorkExp::insert($new_work_exp);
        }
    }


    /**
     * @param $mobile
     * @return mixed
     */
    public static function getResumeDtl($mobile)
    {
        $field = [
            "id", "user_name", "head_img", "sex", "work_st", "weChat", "email", "mobile", "cell_mobile", "edu_id",
            "birth", "work_date", "adv"
        ];
        $nt    = Note::where([
            ['mobile', "=", $mobile], ['status', "=", Status::REGULAR], [
                'is_deleted', '=',
                Status::NOT_DELETE
            ]
        ])->select($field)->first();

        if ($nt) {
            # 获取头像

            if ($nt->work_exp) {
                $work_exp_alias = $project_exp_alias = [];
                foreach ($nt->work_exp as $item) {
                    if ($item["tp"] == 1) {
                        $work_exp_alias[] = $item;
                    } else {
                        $project_exp_alias[] = $item;
                    }
                }
                $nt->work_exp_alias    = $work_exp_alias;
                $nt->project_exp_alias = $project_exp_alias;
                unset($nt->work_exp);
            }

            if ($nt->notes_intention) {
                $nt->notes_intention;
            }

            if ($nt->educational_back) {
                $nt->educational_back;
            }



            $nt->annex_path = $nt->att_name = $nt->annex_created_at = $nt->education_info = "";
            $tmp            = self::GetAnnex($mobile);
            if ($tmp && count($tmp) > 0) {
                $nt->annex_path       = $tmp["path"];
                $nt->att_name         = $tmp["name"];
                $nt->annex_created_at = $tmp["created_at"];
            }

            if ($nt->edu_id) {
                $nt->education_info = Status::EDUCATION[$nt->edu_id];
            }
        }

        return $nt;
    }


    /**
     * @param $mobile
     * @param $path
     * @param $type
     * @param $fileName
     * @return mixed
     * @throws \Exception
     */
    public static function createResumeMidd($mobile, $path, $type, $fileName)
    {
        $connection = DB::connection('mysql');
        $connection->beginTransaction();
        try {
            $res['path']       = $path;
            $res['created_at'] = time();
            $id                = Resources::insertGetId($res);
            if ($type == 1) {
                $nt = DB::table('recruit_notes')->where(
                    [
                        ["mobile", "=", $mobile],
                        ["is_deleted", "=", Status::NOT_DELETE],
                        ["status", "=", Status::REGULAR]
                    ]
                )->first();

                if (!$nt) {
                    DB::table('recruit_notes')->insert(['mobile' => $mobile, "head_img" => $id, "created_at" => time()]);
                } else {
                    DB::table("recruit_notes")->where("mobile", $mobile)->update(
                        ['head_img' => $id, 'updated_at' => time()]);
                }

                $connection->commit();
                return $id;
            } else {
                $data['att_name']   = $fileName;
                $data['mobile']     = $mobile;
                $data['res_id']     = $id;
                $data['created_at'] = time();
                NotesMiddle::where("mobile", $mobile)->update(
                    ['status' => Status::NOT_DELETE, 'is_deleted' => Status::DELETED, 'updated_at' => time()]);
                NotesMiddle::insert($data);
                $connection->commit();
                return $id;
            }

        } catch (\Exception $exception) {
            DB::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 设置获取头像
     * @param $id
     * @return mixed
     */
    public static function setHeadUpload($id)
    {
        Note::where('mobile', Helper::pcByMobile())->update(['head_img' => $id]);

        # 获取头像
        $resource = $mobile = DB::table('recruit_resources')->select(["id", "path"])->find($id);
        return ["path" => Helper::buildQiNiuUrl($resource->path)];
    }


    /**
     * @param $mobile
     * @return mixed
     */
    public static function delResumeLogic($mobile)
    {
        return NotesMiddle::where("mobile", $mobile)->update(
            ['status' => Status::NOT_DELETE, 'is_deleted' => Status::DELETED, 'updated_at' => time()]);
    }

    /**
     * @param $mobile
     * @param $attName
     * @return mixed
     */
    public static function editResumeName($mobile, $attName)
    {
        return NotesMiddle::where([
            ["mobile", '=', $mobile], ["status", '=', Status::REGULAR], [
                "is_deleted", '=',
                Status::NOT_DELETE
            ]
        ])->update(
            ['att_name' => $attName, 'updated_at' => time()]);
    }


    /**
     * @param $id
     * @return array
     */
    public static function delResume($id)
    {
        $Note       = Note::find($id);
        $connection = DB::connection('mysql');
        $connection->beginTransaction();
        try {
            Note::where("mobile", $Note->mobile)->update(
                ['status' => Status::NOT_DELETE, 'is_deleted' => Status::DELETED, 'updated_at' => time()]);

            NotesMiddle::where("mobile", $Note->mobile)->update(
                ['status' => Status::NOT_DELETE, 'is_deleted' => Status::DELETED, 'updated_at' => time()]);

            WorkExp::where([['mobile', '=', $Note->mobile]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
            NotesIntention::where([['mobile', '=', $Note->mobile]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );

            EducationalBack::where([['mobile', '=', $Note->mobile]])->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }
}
